package com.dreamcode.anfeedreader.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.util.Log;

public class IOUtils {
	private static int kDEFAULT_CHUNK_SIZE = 256;
	public IOUtils(){}
	
	public URL getDefaultFavicon(String rssurl){
		try{
			URL orig = new URL(rssurl);

			URL iconUrl = new URL(orig.getProtocol(), orig.getHost(),
			  orig.getPort(), "/favicon.ico");
			
			return iconUrl;
		}catch (MalformedURLException e){
			Log.d("", Log.getStackTraceString(e));
			return null;
		}
	}

	public byte[] updateFavicon(Context ctx, String iconUrl)
			throws MalformedURLException {
		try {
			return loadBytesFromURL(ctx, new URL(iconUrl));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public byte[] loadBytesFromURL(Context ctxU, URL url) throws IOException {
		byte[] b = null;
		URLConnection con = url.openConnection();
		int size = con.getContentLength();
		InputStream in = null;

		try {
			if ((in = con.getInputStream()) != null)
				b = (size != -1) ? loadBytesFromStreamForSize(in, size)
						: loadBytesFromStream(in);
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException ioe) {
				}
		}
		return b;
	}

	public byte[] loadBytesFromStream(InputStream in) throws IOException {
		return loadBytesFromStream(in, kDEFAULT_CHUNK_SIZE);
	}
	
	public byte[] loadBytesFromStreamForSize(InputStream in, int size)
			throws IOException {
		int count, index = 0;
		byte[] b = new byte[size];

		// read in the bytes from input stream
		while ((count = in.read(b, index, size)) > 0) {
			size -= count;
			index += count;
		}
		return b;
	}

	public byte[] loadBytesFromStream(InputStream in, int chunkSize)
			throws IOException {
		if (chunkSize < 1)
			chunkSize = kDEFAULT_CHUNK_SIZE;

		int count;
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		byte[] b = new byte[chunkSize];
		try {
			while ((count = in.read(b, 0, chunkSize)) > 0)
				bo.write(b, 0, count);
			byte[] thebytes = bo.toByteArray();
			return thebytes;
		} finally {
			bo.close();
			bo = null;
		}
	}
	
}
